package org.wsff.tools.api.gateway.impl;

import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.wsff.tools.api.gateway.manager.AbstractProxyManager;
import org.wsff.tools.api.gateway.core.ProxyFilter;
import org.wsff.tools.api.gateway.core.ProxyInvoker;
import org.wsff.tools.api.gateway.core.ProxyValidator;
import org.wsff.tools.api.gateway.impl.spring.AopTargetUtils;
import org.wsff.tools.api.gateway.impl.spring.SpringContextHolder;

import com.google.common.collect.Lists;

/**
 * 服务提供者默认实现
 *
 * @author ryan
 * @version Id: GenericProxyManager.java, v 0.1 2022-01-19 18:39 ryan Exp $$
 */
@Slf4j
@Service("springProxyManager")
public class GenericProxyManager<Request extends Serializable, Response extends Serializable> extends AbstractProxyManager<Request, Response> {

    /**
     * 获取所有 ProxyFilter
     *
     * @return filter集合
     */
    @Override
    protected List<ProxyFilter<Request, Response>> getAllProxyFilters() {
        Map<String, ProxyFilter> filterMap = SpringContextHolder.getContext().getBeansOfType(ProxyFilter.class, false, true);
        List<ProxyFilter<Request, Response>> filters = Lists.newArrayList();
        for (Map.Entry<String, ProxyFilter> entry : filterMap.entrySet()) {
            filters.add((ProxyFilter<Request, Response>) entry.getValue());
        }
        return filters;
    }

    /**
     * 获取所有ProxyValidator
     *
     * @return 验证器集合
     */
    @Override
    protected List<ProxyValidator<Request>> getAllProxyValidators() {
        Map<String, ProxyValidator> validatorMap = SpringContextHolder.getContext().getBeansOfType(ProxyValidator.class, false, true);
        List<ProxyValidator<Request>> validators = Lists.newArrayList();
        for (Map.Entry<String, ProxyValidator> entry : validatorMap.entrySet()) {
            validators.add((ProxyValidator<Request>) entry.getValue());
        }
        return validators;

    }

    /**
     * 获取所有ProxyInvoker
     *
     * @return 服务集合
     */
    @Override
    protected List<ProxyInvoker<Request, Response>> getAllProxyInvokers() {
        Map<String, ProxyInvoker> invokerMap = SpringContextHolder.getContext().getBeansOfType(ProxyInvoker.class, false, true);
        List<ProxyInvoker<Request, Response>> invokers = Lists.newArrayList();
        for (Map.Entry<String, ProxyInvoker> entry : invokerMap.entrySet()) {
            invokers.add((ProxyInvoker<Request, Response>) entry.getValue());
        }
        return invokers;

    }

    /**
     * 获取服务原始对象
     *  服务对象可能会被代理，需要获取被代理的原始对象
     *
     * @param obj 代理对象
     * @return 原始对象
     */
    @Override
    protected Object getOriginalObject(Object obj) {
        return AopTargetUtils.getTarget(obj);
    }

}
